package com.zxy;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class SnakeGameGUI extends JFrame implements KeyListener {
    private SnakeGame game;
    private Timer timer;

    public SnakeGameGUI(int width, int height, int blockSize) {
        super("贪吃蛇游戏");
        game = new SnakeGame(width, height, blockSize);

        JPanel panel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                game.draw(g);
            }
        };
        panel.setPreferredSize(new Dimension(width, height));
        panel.setBackground(Color.BLACK);
        panel.setFocusable(true);
        panel.addKeyListener(this);
        add(panel);

        timer = new Timer(100, e -> {
            game.move();
            repaint();
            if (game.isGameOver()) {
                timer.stop();
                JOptionPane.showMessageDialog(this, "游戏结束！");
            }
        });
        timer.start();

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }

    @Override
    public void keyTyped(KeyEvent e) {}

    @Override
    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();
        if (keyCode == KeyEvent.VK_UP) {
            game.changeDirection(SnakeGame.Direction.UP);
        } else if (keyCode == KeyEvent.VK_DOWN) {
            game.changeDirection(SnakeGame.Direction.DOWN);
        } else if (keyCode == KeyEvent.VK_LEFT) {
            game.changeDirection(SnakeGame.Direction.LEFT);
        } else if (keyCode == KeyEvent.VK_RIGHT) {
            game.changeDirection(SnakeGame.Direction.RIGHT);
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {}

    public static void main(String[] args) {
        new SnakeGameGUI(400, 400, 20); // 创建一个400x400的游戏窗口，每个方块大小为20
    }
}
